package com.shlh.saas.config;

import com.shlh.saas.common.UserContext;
import com.shlh.saas.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT认证拦截器
 */
@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenPrefix}")
    private String tokenPrefix;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 清除上一个请求可能残留的用户信息
        UserContext.clear();
        
        // 获取请求头中的token
        String authHeader = request.getHeader(tokenHeader);
        
        // 如果请求头中有token，则解析token
        if (authHeader != null && authHeader.startsWith(tokenPrefix)) {
            // 去除Bearer前缀
            String token = authHeader.substring(tokenPrefix.length());
            
            try {
                // 从token中提取用户ID
                Long userId = jwtUtil.extractUserId(token);
                
                // 设置到ThreadLocal中
                UserContext.setUserId(userId);
                
                return true;
            } catch (Exception e) {
                // token解析失败，不设置用户信息
                return true;
            }
        }
        
        // 如果没有token，继续处理请求
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求完成后清除用户信息，防止内存泄漏
        UserContext.clear();
    }
} 